package com.zzjx.demo.util;

import com.google.common.eventbus.EventBus;
import com.zzjx.demo.listener.UserInfoEventBusListener;

import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>事件总线处理工具类</p>
 * <li>注意消费者过多或处理性能差会阻塞事件生产者发送</li>
 * <li>注意消费者处理失败抛出异常不影响事件生产者发送</li>
 * @author zhaojiaxu
 * @date 2022/02/20 14:52
 **/
public abstract class EventBusUtils {
    private static ConcurrentHashMap<String, EventBus> EVENT_BUS_CONTEXT = new ConcurrentHashMap<>();
    /**
     * 注册一个监听器[同步]
     *
     * @author zhaojiaxu
     * @date 2022/02/20 15:23
     * @param group 监听器分组
     * @param listener  监听器
     * @return void
     */
    public static void registerEvent(String group, UserInfoEventBusListener listener) {

        EventBus eventBus = getEventBus(group);
        eventBus.register(listener);

    }
    public static void unregisterEvent(String group, UserInfoEventBusListener listener) {
        EventBus eventBus = getEventBus(group);
        if(eventBus!=null){
            eventBus.unregister(listener);
        }
    }

     /**
      * 推送一个事件给对应的监听器
      * @author zhaojiaxu
      * @date 2022/02/20 15:19
      * @param group
      * @param event
      * @return void
      */
    public static <T> void postEvent(String group, T event) {
        EventBus eventBus = getEventBus(group);
        if (eventBus != null && event != null) {
            eventBus.post(event);
        }
    }


    private static EventBus getEventBus(String group) {
        return getEventBus(group, true);
    }

    private static EventBus getEventBus(String group, boolean createIfNotExist) {
        EventBus eventBus = EVENT_BUS_CONTEXT.get(group);
        if (eventBus == null && createIfNotExist) {
            eventBus = new EventBus(group);
            EventBus exist = EVENT_BUS_CONTEXT.putIfAbsent(group, eventBus);
            if (exist != null) {
                eventBus = exist;
            }
        }
        return eventBus;
    }
}

